#! /usr/bin/env python
# -*- coding: utf-8 -*-

# 合肥医保 口罩预约

import random

from selenium import webdriver
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.support.wait import WebDriverWait
import time

wechatUserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) " \
                  "AppleWebKit/537.36 (KHTML, like Gecko) " \
                  "Chrome/53.0.2785.116 " \
                  "Safari/537.36 " \
                  "QBCore/4.0.1295.400 " \
                  "QQBrowser/9.0.2524.400 Mozilla/5.0 (Windows NT 6.1; WOW64) " \
                  "AppleWebKit/537.36 (KHTML, like Gecko) " \
                  "Chrome/53.0.2875.116 " \
                  "Safari/537.36 NetType/WIFI MicroMessenger/7.0.5 " \
                  "WindowsWechat"


def single(userinfo, *args, **kwargs):
    # 加载配置数据  配置chrome浏览器 https://blog.csdn.net/zwq912318834/article/details/78933910
    option = webdriver.ChromeOptions()
    userDir = "C:/Users/Administrator/AppData/Local/Google/Chrome/UserData/Default" + args[0]
    option.add_argument("user-data-dir=" + userDir)  # 注意是/ 从资源管理器粘过来的是\
    option.add_argument('user-agent=' + wechatUserAgent)  # 请求头
    # 设置代理
    options = webdriver.ChromeOptions()  # DesiredCapabilities.CHROME
    desired_capabilities = options.to_capabilities()
    # proxy = "127.0.0.1:9999"
    # desired_capabilities['proxy'] = {
    #     "httpProxy": proxy, "ftpProxy": proxy, "sslProxy": proxy, "noProxy": None,
    #     "proxyType": "MANUAL", "class": "org.openqa.selenium.Proxy", "autodetect": False}
    # chromedriver7下载地址 https://sites.google.com/a/chromium.org/chromedriver/downloads 要对应机器浏览器的版本号 帮助关于chrmoe
    browser = webdriver.Chrome("./driver/chromedriver80.exe", options=option,
                               desired_capabilities=desired_capabilities)
    browser.get('http://kzgm.bbshjz.cn:8000/ncms/mask/book-view')
    # time.sleep(10000)
    while (True):
        try:
            time.sleep(1)
            browser.find_element_by_id("maskForm")
            break
        except:
            browser.refresh()
            pass
    # 显示隐藏的区域
    browser.execute_script("""
        var inputs=document.getElementsByTagName("input")
        for (let i = 0; i < inputs.length; i++) {
            inputs[i].type="auto"
        }
        var inputs=document.getElementsByClassName("mui-input-row")
        inputs[0].style.height="90px"
        inputs[5].style.height="90px"
         """)
    # 设置值
    browser.execute_script('''
            document.getElementById("pharmacyCode").value="10658";
            document.getElementById("pharmacyPhase").value="9:00-13:00";
            document.getElementById("pharmacyPhaseName").value="9:00-13:00/剩余:300个";
            document.getElementById("pharmacyName").value="国胜大药房中央城邦店";
            document.getElementById("reservationNumber").value="5";
            document.getElementById("cardNo").value="{}";
            document.getElementById("name").value="{}";
            document.getElementById("phone").value="{}";
        '''.format(userinfo[0], userinfo[1], userinfo[2]))
    # 新添加个按纽
    browser.execute_script("""
                var oldBt=document.getElementsByTagName("button")[0];
                oldBt.removeAttribute("disabled")
                
                var button=document.createElement("button");
                button.setAttribute("onclick","bindNext()")
                button.innerText="新提交";
                button.style.background="red"
                button.type="button"
                var div=document.getElementById("maskForm");
                div.appendChild(button);
        
        """)
    time.sleep(3 * 60)  # 方法结束后浏览器就关掉了，让线程等待
    browser.execute_script('bindNext()')
    browser.quit()


def userInfo(info_):
    """
    以#号开头的过滤掉 去掉每行尾部的回车键
    :param info_:
    :return:
    """
    if (info_.startswith("#")):
        return None;
    elif (info_.endswith("\n")):
        info_ = info_[0: len(info_) - 1]
    userInfo = info_.split(",");
    return userInfo;


def loop():
    import threading
    # 同目录下hfkz.txt 格式，姓名,身份证号,手机号
    with open("hfkz.txt", encoding="utf-8") as file:
        infos = file.readlines();
    for index in range(len(infos)):
        _userInfo = userInfo(infos[index])
        if (_userInfo == None):
            continue;
        # print(_userInfo)
        # single(_userInfo, (str(index)))
        threading.Thread(target=single, args=(_userInfo, str(index + random.randint(0, 100)))).start()
        time.sleep(2)
    # print("loop end")


# single(userInfo[0], (str(0)))
loop()
